/*
 * @Description: websocket
 * @Author: 林文琛
 * @Date: 2022-08-19 11:34:50
 * @LastEditTime: 2022-08-19 11:34:56
 * @LastEditors: 林文琛
 */

import { ref } from 'vue'

/** WebSocket */
export class Ws {
    /** ws */
    private ws: WebSocket | null
    /** 连接状态 */
    public socketStatus: boolean
    /** 消息内容 */
    public message: any

    constructor() {
        this.ws = null
        this.socketStatus = false
        this.message = ref()
    }

    /** 建立连接 */
    connect(url: string) {
        this.ws = new WebSocket(url)
        this.ws.onopen = this.onopen.bind(this)
        this.ws.onmessage = this.onmessage.bind(this)
        this.ws.onclose = this.onclose.bind(this)
        this.ws.onerror = this.onerror.bind(this)
    }

    /** 连接成功 */
    onopen() {
        this.socketStatus = true
        console.log('websocket连接成功', this.ws)
    }

    /** 接收消息 */
    onmessage(e: { data: string }) {
        this.message.value = JSON.parse(e.data)
        console.log('接收消息', JSON.parse(e.data))
    }

    /** 连接关闭 */
    onclose() {
        this.socketStatus = false
        console.log('websocket连接关闭')
    }

    /** 连接失败 */
    onerror(e: any) {
        this.socketStatus = false
        console.log('websocket连接失败', e);
    }

    /** 发送消息 */
    send(message: any) {
        if (this.ws && this.socketStatus) {
            this.ws.send(JSON.stringify(message))
            console.log('发送消息', message)
        }
    }
}

